﻿(function ($) {
    // 增加Array扩展
    if (!$.isFunction(Array.prototype.filter)) {
        Array.prototype.filter = function (callback, thisObject) {
            if ($.isFunction(callback)) {
                var res = new Array();
                for (var i = 0; i < this.length; i++) {
                    callback.call(thisObject, this[i], i, this) && res.push(this[i]);
                }
                return res;
            }
        };
    }

    // 增加String扩展
    if (!$.isFunction(String.prototype.trim)) {
        String.prototype.trim = function () {
            if (this == null) return "";
            var trimLeft = /^\s+/, trimRight = /\s+$/;
            return this.replace(trimLeft, "").replace(trimRight, "");
        };
    }

    // 扩展Date
    if (!$.isFunction(Date.prototype.format)) {
        Date.prototype.format = function (format) {
            var o = {
                "M+": this.getMonth() + 1,
                "d+": this.getDate(),
                "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12,
                "H+": this.getHours(),
                "m+": this.getMinutes(),
                "s+": this.getSeconds(),
                "q+": Math.floor((this.getMonth() + 3) / 3),
                "S": this.getMilliseconds()
            };
            var week = {
                0: "日",
                1: "一",
                2: "二",
                3: "三",
                4: "四",
                5: "五",
                6: "六"
            };

            if (/(y+)/.test(format))
                format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

            if (/(E+)/.test(format))
                format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay()]);

            for (var k in o)
                if (new RegExp("(" + k + ")").test(format))
                    format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return format;
        };
    }

    // 扩展format
    $.extend({
        "format": function (source, params) {
            if (params === undefined) {
                return source;
            }
            if (arguments.length > 2 && params.constructor !== Array) {
                params = $.makeArray(arguments).slice(1);
            }
            if (params.constructor !== Array) {
                params = [params];
            }
            $.each(params, function (i, n) {
                source = source.replace(new RegExp("\\{" + i + "\\}", "g"), function () {
                    return n;
                });
            });
            return source;
        }
    });

    // enhance window.console.log
    if (!window.console) {
        window.console = {
            log: function () {

            }
        };
    }
    window.console = window.console || {};
    console.log || (console.log = opera.postError);

    // client
    jQuery.browser = {
        versions: function () {
            var u = navigator.userAgent;
            return {         //移动终端浏览器版本信息
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPod: u.indexOf('iPod') > -1, //是否为iPod或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    }

    $.extend({
        bc: function (options, callback) {
            var data = $.extend({
                remote: true,
                Id: "",
                url: this.url,
                data: {},
                method: "POST",
                htmlTemplate: '<div class="form-group checkbox col-md-3 col-sm-4 col-xs-6"><label role="tooltip" title="{3}"><input type="checkbox" value="{0}" {2}/>{1}</label></div>',
                title: this.title,
                swal: true,
                modal: null,
                callback: null
            }, options);

            if (!data.url || data.url == "") {
                swal('参数错误', '未设置请求地址Url', 'error');
                return;
            }

            if (data.remote && data.url) {
                $.ajax({
                    url: data.url + data.Id,
                    data: data.data,
                    type: data.method,
                    async: true,
                    success: function (result) {
                        success(result);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if ($.isFunction(data.callback)) data.callback(false);
                    }
                });
            }
            function success(result) {
                if ($.isFunction(data.callback)) {
                    data.callback(result);
                }
                if (data.modal !== null) {
                    $("#" + data.modal).modal('hide');
                }
                if (data.swal) {
                    if (result) { swal("成功", data.title, "success"); }
                    else { swal("失败", data.title, "error"); }
                }
            }
        },
        getUID: function (prefix) {
            if (!prefix) prefix = 'lgb';
            do prefix += ~~(Math.random() * 1000000)
            while (document.getElementById(prefix))
            return prefix;
        }
    });

    $.fn.extend({
        fixCollapse: function () {
            var $root = $(this);
            var $collapse = $root.find('a[data-toggle="collapse"]');
            $collapse.each(function () {
                var $this = $(this);
                if ($this.attr('href') != '#') return;
                var $target = $this.parent().next();
                var tId = $.getUID('collapse');
                $target.attr('id', tId);
                $this.attr('href', '#' + tId);
            });
            return this;
        },
        autoScroll: function (options) {
            options = $.extend({ offsetTop: 60, parent: '#main-content' }, options)
            if ($(options.parent).css('overflow') != "auto") options.parent = window;
            var $this = $(this);
            var top = ($this.offset() || { top: 0 }).top;
            var middle = options.offsetTop + $(options.parent).outerHeight() / 2;
            var gaps = options.parent == window ? top - middle + options.offsetTop : $(options.parent).scrollTop() + top + $this.outerHeight() / 2 - middle
            $(options.parent).animate({ scrollTop: gaps }, 500);
        },
        adjustDialog: function () {
            var $modal_dialog = this;
            var m_top = Math.max(0, ($(window).height() - $modal_dialog.height()) / 2);
            $modal_dialog.css({ 'margin': m_top + 'px auto' });
            return this;
        },
        autoCenter: function () {
            var that = this;
            var getHeight = function () {
                return ($(window).height() - $(that).outerHeight()) / 2 + $(document).scrollTop();
            }
            $(window).resize(function () {
                $(that).css({
                    marginTop: getHeight()
                });
            });
            that.animate({ marginTop: "+=" + getHeight() });
        },
        lgbUploadFile: function (options) {
            var $this = $(this);
            var op = typeof options == 'object' && options;
            if (/val/.test(options)) {
                return $this.attr('data-file');
            }
            else {
                var $template = $('<div class="logoImage"><div>点击选择上传图片</div><button type="button" class="btn btn-sm btn-info"><i class="fa fa-trash-o"></i><span>删除</span></button><input class="hidden" type="file" accept="image/bmp,image/png,image/jpg,image/jpeg,image/gif" /></div>').insertAfter($this);
                $this.insertBefore($template.children(":first"));
                if ($this.attr('src')) $template.addClass('open');
                var op = { parent: 'li.quest.open', opItem: '.form-group', titleClass: '.title', resultClass: '.result', subjectTitle: 'subject', opTitle: 'opTitle' };
                return $template.on('click', 'div,img', function () {
                    $(this).parent().children(':file').trigger('click');
                }).on('click', 'button', function () {
                    var $parent = $(this).parent().removeClass('open');
                    $parent.find(':file').val('');
                    $parent.find('img').attr('data-file', '');
                    if($parent.find('img').hasClass(op.subjectTitle)){
                        $parent.parents(op.parent).find(op.titleClass).find('img').attr("src", "");
                    } else if ($parent.find('img').hasClass(op.opTitle)) {
                        var index=$parent.parents('.form-group').index();
                        $parent.parents(op.parent).find(op.resultClass).children().eq(index).find('img').attr("src", "");
                    }
                }).on('change', ':file', function () {
                    var $this = $(this);
                    var files = $this.prop('files');
                    if (files.length > 0) {
                        var reader = new FileReader();
                        reader.onload = function () {
                            var data = this.result;
                            $this.parent().addClass('open').children().not(':file').each(function () {
                                switch (this.tagName.toLowerCase()) {
                                    case 'img':
                                        var $img = $(this).attr('src', data);
                                        var fd = new FormData();
                                        fd.append('file', files[0], files[0].name);
                                        $.bc({
                                            url: '../api/Upload', data: fd, contentType: false, processData: false, swal: false, callback: function (result) {
                                                if (result) {
                                                    $img.attr({ 'src': result.initialPreview[0], 'data-file': result.initialPreviewConfig[0].key });
                                                    if ($img.hasClass(op.subjectTitle)) {
                                                        $img.parents(op.parent).find(op.titleClass).find('img').attr("src", $img.attr("src"));
                                                    }
                                                    else if($img.hasClass(op.opTitle)){
                                                        var index = $img.parents(op.opItem).index();
                                                        $img.parents(op.parent).find(op.resultClass).children().eq(index).find('img').attr("src", $img.attr("src"));
                                                    }
                                                }
                                            }
                                        });
                                        break;
                                }
                            });
                        }
                        reader.readAsDataURL(files[0]);
                    }
                });
            }
        },
        lgbUploadFileTemp: function (options) {
            var $this = $(this);
            var op = typeof options == 'object' && options;
            if (/val/.test(options)) {
                return $this.attr('data-file');
            }
            else {
                var $template = $('<div class="logoImage"><div>点击选择上传模板</div><button type="button" class="btn btn-sm btn-info"><i class="fa fa-trash-o"></i><span>删除</span></button><input class="hidden" type="file" accept=".doc,.docx" /></div>').insertAfter($this);
                $this.insertBefore($template.children(":first"));
                if ($this.text()) $template.addClass('open');
                return $template.on('click', 'div,label', function () {
                    $(this).parent().children(':file').trigger('click');
                }).on('click', 'button', function () {
                    var $parent = $(this).parent().removeClass('open');
                    $parent.find(':file').val('');
                    $parent.find('label').attr('data-file', '');
                    $parent.find('label').text('');
                }).on('change', ':file', function () {
                    var $this = $(this);
                    var files = $this.prop('files');
                    if (files.length > 0) {
                        var reader = new FileReader();
                        reader.onload = function () {
                            var data = this.result;
                            $this.parent().addClass('open').children().not(':file').each(function () {
                                switch (this.tagName.toLowerCase()) {
                                    case 'label':
                                        var $label = $(this);
                                        var fd = new FormData();
                                        fd.append('file', files[0], files[0].name);
                                        $.bc({
                                            url: '../api/Upload', data: fd, contentType: false, processData: false, swal: false, callback: function (result) {
                                                if (result) {
                                                    var str = result.initialPreviewConfig[0].key;
                                                    $label.attr('data-file', str);
                                                    $label.text(str.substr(str.indexOf('-')+1));
                                                }
                                            }
                                        });
                                        break;
                                }
                            });
                        }
                        reader.readAsDataURL(files[0]);
                    }
                });
            }
        },
        lgbTooltip: function (option) {
            if (option == undefined) option = { delay: { "show": 500, "hide": 100 } };
            else if (typeof option == "object") option = $.extend({ delay: { "show": 500, "hide": 100 } }, option);
            $(this).tooltip(option);
            if (option == 'destroy') $(this).removeAttr('data-original-title');
            return this;
        },
        autoValidate: function (rules, messages, handler) {
            var parent = 'body';
            var $wrapper = $('#dialogNew');
            if ($wrapper.length == 1) parent = '#dialogNew';
            // validate
            var $this = $(this);
            if (messages && $.isArray(messages.button)) {
                handler = messages;
                messages = {};
            }
            else {
                messages = $.extend({}, messages);
            }
            $this.validate({
                validClass: "has-success",
                errorClass: "has-error",
                ignore: ".ignore",
                rules: $.extend({}, rules),
                messages: $.extend({}, messages),
                highlight: function (element, errorClass, validClass) {
                    $(element).parents('.form-group').addClass(errorClass).removeClass(validClass);
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).lgbTooltip('destroy').parents('.form-group').removeClass(errorClass).addClass(validClass);
                },
                errorPlacement: function (label, element) {
                    var $ele = $(element);
                    if (!$ele.attr('data-original-title')) $ele.lgbTooltip({ container: parent });
                    $ele.attr('data-original-title', $(label).text());
                    $ele.lgbTooltip('show');
                    $('#' + $ele.attr('aria-describedby')).addClass(this.errorClass);
                }
            });
            if (handler && $.isArray(handler.button)) {
                $.each(handler.button, function (index, btn) {
                    $('#' + btn).on('click', function () {
                        $(this).attr('data-valid', $this.valid());
                    });
                });
            }
        },
        smartTable: function (options) {
            var settings = $.extend({
                method: 'get',                      //请求方式（*）
                toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sortOrder: "desc",                   //排序方式
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                      //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                search: false,                      //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                strictSearch: false,
                showColumns: true,                  //是否显示所有的列
                showRefresh: true,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: false,               //是否启用点击选中行
                //height: 500,                      //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                idField: "Id",
                uniqueId: "Id",                     //每一行的唯一标识，一般为主键列
                showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,                  //是否显示父子表
                clickToSelect: false
            }, options);
            $(this).bootstrapTable(settings);
            var $toolbar = $('div.toolbar');
            $toolbar.on('click', 'a', function (e) {
                e.preventDefault();
                var ctl = $('#' + $(this).attr('id').replace('tb_', 'btn_'));
                ctl.trigger("click");
            }).insertBefore($('div.bootstrap-table > div.fixed-table-toolbar > div.bs-bars'));
            $(settings.toolbar).removeClass('hidden');
        },
        select: function () {
            var $this = $(this);
            $this.each(function (index, element) {
                var $element = $(element);
                var $select = $element.find('button').first();
                $element.on('click', '.dropdown-menu > li > a', function () {
                    var $op = $(this);
                    $select.text($op.text()).attr('data-val', $op.attr('data-val'));
                })
            });
        },
        selectval: function (value) {
            var $this = $(this);
            if (value == undefined) return $this.attr('data-val') || $this.attr('data-default-val');
            $this.find('.dropdown-menu > li > a').each(function (index, element) {
                var $op = $(element);
                var val = $op.attr('data-val');
                if (value == val) {
                    $this.text($op.text()).attr('data-val', val);
                }
            });
        },
        html5edit: function (options) {
            var $this = $(this);
            var op = typeof options == 'object' && options;
            if (/destroy|hide/.test(options)) {
                return $this.toggleClass('open').summernote(options);
            }
            else if (typeof options == 'string') {
                return $this.hasClass('open') ? $this.summernote(options) : $this.html();
            }
            if (!$this.hasClass('open')) {
                op = $.extend({ focus: false, lang: 'zh-CN', height: 80, dialogsInBody: true, btnLoadFile: false }, op);
                if (!$this.attr('data-original-title')) $this.on('click', op, function (event) {
                    var $this = $(this).lgbTooltip('hide');
                    var op = $.extend({ placeholder: $this.attr('placeholder') }, event.data);
                    var $toolbar = $this.toggleClass('open').summernote($.extend({}, op, { focus: true })).next().find('.note-toolbar')
                        .on('click', 'button[data-method]', $this, function (event) {
                            var $this = $(this);
                            switch ($this.attr('data-method')) {
                                case 'submit':
                                    $this.lgbTooltip('destroy');
                                    event.data.toggleClass('open').summernote('destroy');
                                    break;
                                case 'loadFile':
                                    if (event.target.tagName.toLowerCase() == 'input') return;
                                    $(this).lgbTooltip('hide').find(':file').trigger('click');
                                    break;
                            }
                        }).on('click', '.btn-fullscreen', function () {
                            $('#main-content').toggleClass('z51');
                        })
                    var $done = $('<div class="note-btn-group btn-group note-view note-right"><button type="button" class="note-btn btn btn-info btn-sm" tabindex="-1" data-method="submit" title="完成" data-placement="bottom"><i class="fa fa-check"></i></button></div>').appendTo($toolbar).find('button').lgbTooltip({ container: 'body' });
                    if (op.btnLoadFile) {
                        $('<button type="button" class="note-btn btn btn-info btn-sm" tabindex="-1" data-method="loadFile" title="加载模板文件" data-placement="bottom"><i class="fa fa-file-text-o"></i><input class="hidden" type="file" accept="text/html,text/rtf,text/plain" /></button>').insertBefore($done).on('change', function () {
                            var $this = $(this);
                            var files = $this.find(':file').prop('files');
                            if (files.length > 0) {
                                var reader = new FileReader();
                                reader.readAsText(files[0], "GB2312");
                                reader.onload = function (evt) {
                                    $this.parents('.note-editor').find('.note-editable').append($($.format('<div>{0}</div>', evt.target.result)));
                                }
                            }
                        }).lgbTooltip({ container: 'body' });
                    }
                    $('body').find('.note-group-select-from-files [accept="image/*"]').attr('accept', 'image/bmp,image/png,image/jpg,image/jpeg,image/gif');
                }).attr({ title: '点击展开编辑' }).lgbTooltip();
                if (op.focus) $this.trigger('click');
            }
            return this;
        },
        uploadFile: function (options) {
            var $this = $(this);
            if (/val/.test(options)) {
                var data = $this.data('lgb.images');
                return $.isArray(data) ? data.join(',') : "";
            }
            else {
                var op = options;
                var initImagesConfig = []
                $this.fileNameCache = function (url, statusValue) {
                    if (statusValue == undefined) statusValue = true;
                    var $this = this;
                    var urls = $this.data('lgb.images');
                    if (!urls || !$this.attr('multiple')) {
                        urls = [];
                        $this.data('lgb.images', urls);
                    }
                    var fileName = url.split('/').pop();
                    if (statusValue) {
                        urls.push(fileName);
                        initImagesConfig.push({ caption: fileName, size: 0, key: fileName });
                    }
                    else {
                        urls.splice($.inArray(fileName, urls), 1);
                    }
                    return url;
                }
                $this.addPlus = function (status) {
                    var $el = this;
                    if (!$el.attr('multiple')) {
                        var $plus = $el.parent().find('.file-drop-zone-title-plus');
                        if ($plus.length == 0) {
                            $plus = $($.format('<div class="file-drop-zone-title-plus hidden">{0}</div>', op.dropZoneClickTitle));
                            $plus.insertAfter($el.parent().find('.file-preview-thumbnails'));
                        }
                        if (status == 'del' && $el.parent().find('.file-preview-frame').length == 1) $plus.addClass('hidden');
                        else if ($el.parent().find('.file-preview-frame').length > 0) $plus.removeClass('hidden');
                    }
                    return $el;
                }
                op.initialPreview = $this.parent().find('div:hidden').map(function () {
                    return $this.fileNameCache($(this).text());
                }).toArray();
                op.initialPreviewConfig = initImagesConfig;
                if (!$this.attr('multiple')) {
                    $this.on('fileimageloaded', function () {
                        $this.fileinput('upload');
                    })
                }
                return $this.fileinput(op).addPlus().on('fileuploaded', function (event, data) {
                    $this.addPlus().fileNameCache(data.response.initialPreviewConfig[0].key);
                }).on('filedeleted', function (event, key) {
                    $this.addPlus('del').fileNameCache(key, false);
                })
            }
        }
    });

    //fix bug
    $.fn.modal.Constructor.prototype.adjustDialog = function () {
        var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight

        this.$element.css({
            paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
            paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
        })

        // added by Argo
        var $modal_dialog = $(this.$element[0]).find('.modal-dialog');
        $modal_dialog.adjustDialog();
    }
})(jQuery);

$(function () {
    $('.btn-select').select();
});